import React, { useEffect, useState } from 'react'
import { Button, Drawer, Empty, message, Modal, Space, Table, Timeline } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import { getOrgList, addOrg, editOrg, updateOrgStatus } from '@/api/org'
import SearchForm from '@/components/CustomForm/SearchForm'
import { FormInstance, useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import './index.less'
import { ITableData } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import { useFormEdit } from './useFormEdit'
import CustomTable from '@/components/CustomTable'
import { SupplierAppListOptions, STATUSBANDOPTIONS, STATUSNUM, OperationLogType } from '@/constant'
import { PlusOutlined } from '@ant-design/icons'
import useViewLogs from '@/hooks/useViewLogs'
import LogsDrawer from '@/components/LogsDrawer'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useCachePage from '@/hooks/useCachePage'
const Index: React.FC = () => {
  const [form] = useForm()
  const [FormEdit] = useForm()
  const [isModalShow, setIsModalShow] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [searchOptions, setOptions] = useState<IOptionItem[]>([])
  const [ispedding, setispedding] = useState<boolean>(false)
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'id',
    OperationLogType.ORGANIZATION,
  )
  const { setCachePage, getCachePage } = useCachePage()
  const { SupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getOrgList, {
    form: form,
    defaultFieldsParams: {
      statues: [1],
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  let timeout: ITimeoutType
  useEffect(() => {
    // search({ ...params, statues: [1] })
    handleCacheData()
  }, [])
  const onConfirm = async (values: any) => {
    setispedding(true)
    const id = FormEdit.getFieldValue('id')
    let res
    // orgType 0七色纺 1供应商 目前只做供应商的组织新建
    if (!isEdit) {
      res = await addOrg({ orgType: 1, ...values }).finally(() => setispedding(false))
    } else {
      res = await editOrg({ id, orgType: 1, ...values }).finally(() => setispedding(false))
    }
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search(params)
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
    FormEdit.resetFields()
  }
  const onEdit = (info: ITableData) => {
    FormEdit.setFieldsValue({
      ...info,
      suppliers: info?.supplierPairs?.map((item) => item.id),
    })
    setIsEdit(true)
    setIsModalShow(true)
  }
  const handleSearch = (newValue = '') => {
    if (timeout) {
      clearTimeout(timeout)
      timeout = null
    }
    const getOptions = async () => {
      const res = await getOrgList<ITableData>({
        current: 1,
        size: 10,
        orgNameKeyWord: newValue,
      })
      if (res.code === 200) {
        const data =
          res?.data?.list?.map((item) => {
            return {
              label: item.name,
              value: item.id,
            }
          }) || []
        setOptions(data)
      }
    }
    timeout = setTimeout(getOptions, 500)
  }
  const onStatus = async (info: ITableData) => {
    const res = await updateOrgStatus({
      status: info.status == STATUSNUM.CLOSE ? STATUSNUM.OPEN : STATUSNUM.CLOSE,
      id: info.id,
    })
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
    }
  }
  const onValuesChange = (changedValues: any, trimKeys: string[], form: FormInstance) => {
    trimKeys.forEach((key) => {
      if (changedValues[key]) {
        const trimmedKey = changedValues[key].trim()
        form.setFieldsValue({
          [key]: trimmedKey,
        })
      }
    })
  }
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      const paramsData = {
        ...params,
        orgIds: cacheData?.orgIds != null ? [cacheData?.orgIds] : null,
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      form.setFieldsValue({
        ...cacheData,
      })
      setOptions(cacheData?.searchOptions || [])
      delete cacheData?.searchOptions
      search({
        ...cacheData,
        orgIds: cacheData?.orgIds != null ? [cacheData?.orgIds] : null,
      })
    }
  }

  return (
    <PageContainer className="orgmgr_page">
      <SearchForm
        params={params}
        form={form}
        searchConfig={[
          {
            label: '组织名称',
            name: 'orgIds',
            type: 'Select',
            option: searchOptions,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearch,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: '组织状态',
            name: 'statues',
            type: 'Select',
            option: STATUSBANDOPTIONS,
            config: {
              mode: 'multiple',
              optionFilterProp: 'label',
            },
          },
        ]}
        onFinish={(vals: any) => {
          console.log(vals, 'vals')
          const cacheData = {
            ...vals,
            orgIds: vals?.orgIds ? [vals?.orgIds] : null,
            statues: vals?.statues?.length > 0 ? vals.statues : null,
          }
          search({ ...cacheData })
          setCachePage({
            ...cacheData,
            orgIds: vals?.orgIds > 0 ? vals?.orgIds : null,
            searchOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          const paramsData = {
            current: 1,
            size: 10,
            statues: [1],
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
        initialValues={{ statues: [] }}
        extra={
          <div className="table_extra_flex">
            <Button
              type="primary"
              onClick={() => {
                setIsModalShow(true)
                setIsEdit(false)
              }}
              icon={<PlusOutlined />}
            >
              新建组织
            </Button>
          </div>
        }
      ></SearchForm>
      <CustomTable bordered columns={useIndexColumns(onEdit, onStatus, viewLogs, params)} {...tableProps} />
      <Drawer
        title={isEdit ? '编辑组织' : '新建组织'}
        open={isModalShow}
        maskClosable
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button
                type="primary"
                onClick={() => FormEdit.validateFields().then((values) => onConfirm(values))}
                loading={ispedding}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          onValuesChange={(changedValues) => onValuesChange(changedValues, ['name', 'code', 'description'], FormEdit)}
          editConfig={useFormEdit({
            SupplierAppListOptions,
            isEdit,
            SupplierOption,
            handleSearchSupplier,
          })}
          form={FormEdit}
        />
      </Drawer>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
    </PageContainer>
  )
}

export default Index
